require "bit"

function string.fromHex(hex)
    return hex:gsub("[%s%p]", ""):gsub("%x%x", function(c)
        return string.char(tonumber(c, 16))
    end)
end
--- crc8校验,多项式省水利厅
---@param str any
---@return crcval number
function crc8(str)
    local CRC, POLYNOMIAL = 0x00, 0xE5
    for i = 1, #str do
        CRC = bit.bxor(CRC, str:byte(i))
        for j = 1, 8 do
            if bit.band(CRC, 0x80) ~= 0 then -- 最高位是1就和多项式异或运算，0不需要异或
                CRC = bit.bxor(CRC, POLYNOMIAL)
            end
            CRC = bit.lshift(CRC, 1)
        end
    end
    return bit.band(CRC, 0xFF)
end
str = "000003e8"
--str = str:fromHex()
val = tonumber(str,16)
print(val)
-- print(crc8(str:fromHex()))
